<template>
    <div class="feedback-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <ChatDotRound />
                        </el-icon>
                        <span>用户反馈</span>
                    </div>
                    <div class="header-right">
                        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleStatusChange"
                            class="status-filter">
                            <el-option label="未查看" :value="0" />
                            <el-option label="已查看" :value="1" />
                        </el-select>
                        <div class="search-box">
                            <el-input v-model="searchQuery" placeholder="请输入反馈内容搜索" clearable @clear="handleSearch"
                                @keyup.enter="handleSearch">
                                <template #suffix>
                                    <el-icon class="search-icon" @click="handleSearch">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                    </div>
                </div>
            </template>

            <el-table :data="feedbackList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="type" label="类型" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getFeedbackType(row.type)">
                            {{ row.type }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="content" label="反馈内容">
                    <template #default="{ row }">
                        <span class="content-preview" @click="handleView(row)">
                            {{ getContentPreview(row.content) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="contact" label="联系方式" />
                <el-table-column prop="createTime" label="反馈时间" align="center">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '已查看' : '未查看' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleView(row)">
                            <el-icon>
                                <View />
                            </el-icon>查看
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[8, 10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
            </div>
        </el-card>

        <!-- 查看反馈详情对话框 -->
        <el-dialog title="反馈详情" v-model="viewDialogVisible" width="600px">
            <div class="feedback-detail">
                <div class="feedback-header">
                    <el-tag :type="getFeedbackType(currentFeedback?.type)">
                        {{ currentFeedback?.type }}
                    </el-tag>
                    <span class="feedback-time">{{ formatDateTime(currentFeedback?.createTime) }}</span>
                </div>
                <div class="feedback-content">{{ currentFeedback?.content }}</div>
                <div class="feedback-contact">联系方式：{{ currentFeedback?.contact }}</div>
                <div v-if="currentFeedback?.images" class="feedback-images">
                    <div class="images-title">相关截图：</div>
                    <div class="image-list">
                        <el-image v-for="(url, index) in imageList" :key="index" :src="url"
                            :preview-src-list="imageList" fit="cover" class="image-item" />
                    </div>
                </div>
            </div>
            <template #footer>
                <el-button @click="viewDialogVisible = false">关闭</el-button>
                <el-button v-if="currentFeedback?.status === 0" type="primary" @click="handleMarkAsRead"
                    :loading="markingAsRead">
                    我已查看
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, Search, View, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const feedbackList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 查看详情相关
const viewDialogVisible = ref(false)
const currentFeedback = ref(null)

// 计算图片列表
const imageList = computed(() => {
    if (!currentFeedback.value?.images) return []
    try {
        return JSON.parse(currentFeedback.value.images)
    } catch (e) {
        return []
    }
})

// 获取反馈列表
const getFeedbackList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/feedback/list',
            method: 'get',
            params: {
                page: currentPage.value,
                size: pageSize.value,
                content: searchQuery.value,
                status: statusFilter.value
            }
        })
        feedbackList.value = res.data.records
        console.log(feedbackList.value)

        console.log(feedbackList.value)
        total.value = res.data.total
    } catch (error) {
        console.error('获取反馈列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 获取反馈类型样式
const getFeedbackType = (type) => {
    const typeMap = {
        '功能建议': 'success',
        '问题反馈': 'warning',
        '其他': 'info'
    }
    return typeMap[type] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 查看反馈
const handleView = (row) => {
    currentFeedback.value = row
    viewDialogVisible.value = true
}

// 删除反馈
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该反馈记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request({
                url: `/feedback/${row.id}`,
                method: 'delete'
            })
            ElMessage.success('删除成功')
            getFeedbackList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getFeedbackList()
}

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val
    getFeedbackList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getFeedbackList()
}

// 获取内容预览
const getContentPreview = (content) => {
    if (!content) return ''
    return content.length > 15 ? content.substring(0, 15) + '...' : content
}

// 添加标记已读状态
const markingAsRead = ref(false)

// 添加标记已读方法
const handleMarkAsRead = async () => {
    if (!currentFeedback.value) return

    markingAsRead.value = true
    try {
        await request({
            url: `/feedback/status/${currentFeedback.value.id}`,
            method: 'put',
            data: { status: 1 }
        })
        currentFeedback.value.status = 1
        // 更新列表中的状态
        const index = feedbackList.value.findIndex(item => item.id === currentFeedback.value.id)
        if (index !== -1) {
            feedbackList.value[index].status = 1
        }
        ElMessage.success('已标记为已查看')
        viewDialogVisible.value = false
    } catch (error) {
        console.error('更新状态失败:', error)
        ElMessage.error('操作失败')
    } finally {
        markingAsRead.value = false
    }
}

const statusFilter = ref(null)

const handleStatusChange = () => {
    currentPage.value = 1
    getFeedbackList()
}

onMounted(() => {
    getFeedbackList()
})
</script>

<style scoped>
.feedback-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.search-box {
    width: 250px;
}

.search-icon {
    cursor: pointer;
    color: #606266;
}

.search-icon:hover {
    color: #409EFF;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.feedback-detail {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
}

.feedback-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.feedback-content {
    color: #333;
    line-height: 1.6;
    margin: 15px 0;
    white-space: pre-wrap;
}

.feedback-contact {
    color: #606266;
    margin: 10px 0;
}

.feedback-images {
    margin-top: 20px;
}

.images-title {
    margin-bottom: 10px;
    color: #606266;
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.image-item {
    width: 100px;
    height: 100px;
    border-radius: 4px;
    cursor: pointer;
}

.image-item:hover {
    opacity: 0.8;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

:deep(.el-avatar) {
    background: #409EFF;
}

.content-preview {
    cursor: pointer;
    color: #409EFF;
}

.content-preview:hover {
    opacity: 0.8;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.status-filter {
    width: 120px;
}
</style>